import java.util.HashMap;
import java.util.Map;

class Solution {
    public int findMaxLength1(int[] nums) {
        // 暴力枚举
        int len = 0;
        for (int i = 0; i < nums.length; i++) {
            int count_0 = 0;
            int count_1 = 0;
            int j = i;
            for (; j < nums.length; j++) {
                if (nums[j] == 0) {
                    count_0++;
                } else {
                    count_1++;
                }
                if (count_0 == count_1) { // 遍历一次，就统计更新一次
                    len = Math.max(len, (j-i+1));
                }
            }
        }
        return len;
    }

    public int findMaxLength2(int[] nums) {
        // 前缀和优化处理（不如人意版）
        int n = nums.length;
        int[] virtual_nums = new int[n+1];
        for(int i = 0; i < n; i++) {
            int target = nums[i] == 0 ? -1 : 1;
            virtual_nums[i+1] = virtual_nums[i] + target;
        }
        // 从前缀数组的后面开始遍历
        for (int i = n; i > 0; i--) {
            if (virtual_nums[i] == 0) { // 这个位置的0、1数量是相等的
                return i;
            }
        }
        return 0;
    }


    public int findMaxLength(int[] nums) {
        // 前缀和优化处理
        Map<Integer, Integer> hash = new HashMap<>();
        hash.put(0, -1);
        int sum = 0;
        int len = 0;
        for (int i = 0; i < nums.length; i++) {
            int target = nums[i] == 0 ? -1 : 1;
            sum += target;
            if (hash.containsKey(sum)) {
                len = Math.max(len, i-hash.get(sum));
            } else {
                hash.put(sum, i);
            }
        }
        return len;
    }
}